package com.zby.admin.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zby.admin.mapper.AddressMapper;
import com.zby.admin.pojo.Address;
import com.zby.admin.pojo.dto.AddAddressDto;
import com.zby.admin.pojo.dto.AddressDto;
import com.zby.admin.pojo.vo.AddressVo;
import com.zby.admin.service.AddressService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AddressServiceImp extends ServiceImpl<AddressMapper, Address> implements AddressService {
    
    @Resource
    private AddressMapper addressMapper;
    
    @Override
    public boolean addAddress(AddAddressDto addressDto, HttpServletRequest request) {
        // 从session中获取用户ID
        HttpSession session = request.getSession();
        Object userIdObj = session.getAttribute("userId");
        
        if (userIdObj == null) {
            return false;
        }
        
        // 检查addressDto是否为null
        if (addressDto == null) {
            return false;
        }
        
        // 将AddAddressDto转换为Address实体
        Address address = new Address();
        try {
            BeanUtils.copyProperties(addressDto, address);
        } catch (Exception e) {
            // 处理属性拷贝异常
            return false;
        }
        
        Long userId = Long.valueOf(userIdObj.toString());
        address.setUserId(userId);
        
        // 如果这是用户设置的第一个地址，则设为默认地址
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<Address> existingAddresses = addressMapper.selectList(queryWrapper);
        
        if (existingAddresses.isEmpty()) {
            address.setIsDefault(1); // 设为默认地址
        } else if (address.getIsDefault() == null) {
            address.setIsDefault(0); // 非默认地址
        }
        
        // 插入地址信息
        return addressMapper.insert(address) > 0;
    }
    
    @Override
    public List<AddressVo> getAddressListByUserId(HttpServletRequest request) {
        // 从session中获取用户ID
        HttpSession session = request.getSession();
        Object userIdObj = session.getAttribute("userId");
        
        if (userIdObj == null) {
            // 返回空列表
            return new ArrayList<>();
        }
        
        Long userId = Long.valueOf(userIdObj.toString());
        
        // 查询该用户的所有地址
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<Address> addressList = addressMapper.selectList(queryWrapper);
        
        // 转换为AddressVo列表
        return addressList.stream().map(address -> {
            AddressVo addressVo = new AddressVo();
            try {
                BeanUtils.copyProperties(address, addressVo);
            } catch (Exception e) {
                // 处理属性拷贝异常
                return null;
            }
            return addressVo;
        }).filter(addressVo -> addressVo != null) // 过滤掉转换失败的项
        .collect(Collectors.toList());
    }
    
    @Override
    public boolean updateAddress(AddressDto addressDto, HttpServletRequest request) {
        // 从session中获取用户ID
        HttpSession session = request.getSession();
        Object userIdObj = session.getAttribute("userId");
        
        if (userIdObj == null || addressDto == null || addressDto.getId() == null) {
            return false;
        }
        
        Long userId = Long.valueOf(userIdObj.toString());
        
        // 检查地址是否存在且属于当前用户
        Address existingAddress = addressMapper.selectById(addressDto.getId());
        if (existingAddress == null || !existingAddress.getUserId().equals(userId)) {
            return false;
        }
        
        // 将AddressDto转换为Address实体
        Address address = new Address();
        try {
            BeanUtils.copyProperties(addressDto, address);
        } catch (Exception e) {
            // 处理属性拷贝异常
            return false;
        }
        
        // 保持用户ID不变
        address.setUserId(userId);
        
        // 更新地址信息
        return addressMapper.updateById(address) > 0;
    }
    
    @Override
    public boolean deleteAddress(Long id, HttpServletRequest request) {
        // 从session中获取用户ID
        HttpSession session = request.getSession();
        Object userIdObj = session.getAttribute("userId");
        
        if (userIdObj == null || id == null) {
            return false;
        }
        
        Long userId = Long.valueOf(userIdObj.toString());
        
        // 检查地址是否存在且属于当前用户
        Address existingAddress = addressMapper.selectById(id);
        if (existingAddress == null || !existingAddress.getUserId().equals(userId)) {
            return false;
        }
        
        // 删除地址
        return addressMapper.deleteById(id) > 0;
    }

    @Override
    public boolean setDefault(Long id, HttpServletRequest request) {
        // 获取用户ID
        Object userId = request.getSession().getAttribute("userId");
        if (userId == null) {
            return false;
        }
        Long userIdLong = Long.parseLong(userId.toString());

        // 检查地址是否存在且属于当前用户
        Address existingAddress = addressMapper.selectById(id);
        if (existingAddress == null || !existingAddress.getUserId().equals(userIdLong)) {
            return false;
        }
        // 将旧的默认地址设为非默认
        QueryWrapper<Address> queryWrapper = new QueryWrapper<Address>().eq("user_id", userIdLong).eq("is_default", 1);
        // 查询当前用户的默认地址
        List<Address> defaultAddresses = addressMapper.selectList(queryWrapper);

        // 将所有默认地址设置为非默认
        for (Address address : defaultAddresses) {
            address.setIsDefault(0);
            addressMapper.updateById(address);
        }
        // 将指定地址设置为默认地址
        existingAddress.setIsDefault(1);
        return addressMapper.updateById(existingAddress) > 0;

    }
}